import axios from 'axios';

const instance = axios.create({
  baseURL: '',
  timeout: 1000,
  responseType: 'json'
});

/**
 * 替换url中的参数
 * @param {string} url 接口路径
 * @param {AnyObject} params
 * @return {string}
 */
function replaceParams(url: string, params: AnyObject) {
  url.replace(/\{([\w]+)\}/g, (str, $1) => {
    return params[$1];
  });
  return '';
}

function parseRes(res: AnyObject) {
  let { data, headers } = res;

  data = data.data && data.data;
  return {
    data,
    headers
  } as ResType;
}

async function get(
  url: string, data?: AnyObject, params?: AnyObject, opt?: AnyObject
) {
  if (params) url = replaceParams(url, params);
  try {
    const res = await instance.get(url, { params: data, ...(opt || {}) });

    return parseRes(res);
  } catch (err) {
    console.warn(err);
  }
}

async function post(
  url: string, data?: AnyObject, params?: AnyObject, opt?: AnyObject
) {
  if (params) url = replaceParams(url, params);
  try {
    const res = await instance.post(url, data, { ...(opt || {}) });

    return parseRes(res);
  } catch (err) {
    console.warn(err);
  }
}

async function put(
  url: string, data?: AnyObject, params?: AnyObject, opt?: AnyObject
) {
  if (params) url = replaceParams(url, params);

  if (params) url = replaceParams(url, params);
  try {
    const res = await instance.put(url, data, { ...(opt || {}) });

    return parseRes(res);
  } catch (err) {
    console.warn(err);
  }
}


async function del(
  url: string, data?: AnyObject, params?: AnyObject, opt?: AnyObject
) {
  if (params) url = replaceParams(url, params);
  try {
    const res = await instance.delete(url, { params: data, ...(opt || {}) });

    return parseRes(res);
  } catch (err) {
    console.warn(err);
  }
}

export default {
  get,
  post,
  put,
  delete: del
} as AnyObject;
